using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using SurveyHost.Core;
using System.Data.SqlClient;

namespace SurveyHost.Web.Participant
{
    public partial class ConsentForm : System.Web.UI.Page
    {
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            bool consented = StatusHelper.CurrentUserHasConsented();
            bool admin = User.IsInRole("Admin");
            Guid g = WebUtil.CurrentUserId();
            if (!admin && StatusHelper.IsCompleted(g) && !StatusHelper.UserIsValid(g))
                Response.Redirect("NonParticipating.aspx", true);
            if (!admin && consented)
                Response.Redirect("ParticipantValidation.aspx", true);
            _agreeCheckbox.Enabled = !admin;
            _disagreeCheckbox.Enabled = !admin;
        }

        
        protected void _agreeCheckbox_CheckedChanged(object sender, EventArgs e)
        {
            if (!IsValid || User.IsInRole("Admin")) return;
            try
            {
                StatusHelper.Consent(WebUtil.CurrentUserId(), "(consent given)");
            }
            catch (SqlException sex)
            {
                LogHelper.Exception(sex, "Exception thrown when attempting to register consent");
                throw;
            }
            Response.Redirect("ParticipantValidation.aspx", true);

        }

        protected void _disagreeCheckbox_CheckedChanged(object sender, EventArgs e)
        {
            //TODO:  This probably doesn't work.  Durh.
            if (!IsValid || User.IsInRole("Admin")) return;
            try
            {
                StatusHelper.Consent(WebUtil.CurrentUserId(), "(consent not given)");
                //HACK:  This is a backup way to make sure non-consenters can get through without having to redo the DAL or security
                StatusHelper.SetValidationStatus(WebUtil.CurrentUserId(), false, false);
            }
            catch (SqlException sex)
            {
                LogHelper.Exception(sex, "Exception thrown when attempting to register consent");
                throw;
            }
            Response.Redirect("NonParticipating.aspx", true);
        }

        
    }
}
